package hhm.android.machine

import android.Manifest
import android.bluetooth.BluetoothAdapter
import android.content.Intent
import android.os.Bundle
import android.view.View
import androidx.activity.result.ActivityResultLauncher
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.scwang.smart.refresh.layout.SmartRefreshLayout
import com.tbruyelle.rxpermissions3.RxPermissions
import hhm.android.library.utils.OnMultiClickListener
import hhm.android.library.utils.SpacesItemDecoration
import hhm.android.machine.bluetooth.BindToothBrushOneActivity
import hhm.android.machine.bluetooth.BindToothBrushThreeActivity
import hhm.android.machine.height.BindHeightOneActivity
import hhm.android.machine.height.BindHeightThreeActivity
import hhm.android.machine.weight.BindWeightOneActivity
import hhm.android.machine.weight.BindWeightThreeActivity
import siau.android.base.*
import siau.android.http.model.GetListTypeModel
import siau.android.http.model.PageNumAndPageSizeRequest
import siau.android.library.KeyString

@Route(path = MACHINE_ROUTER)
class SelectMachineListActivity : SBBaseActivity() {
    private val locationPermissions = arrayOf(
        Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION
    )
    lateinit var srl: SmartRefreshLayout
    lateinit var recycler: RecyclerView
    var pageNo = 1
    var pageSize = 10
    private var list = ArrayList<GetListTypeModel>()
    lateinit var adapter: SelectMachineListAdapter
    private val REQUEST_ENBLE_BT = 5555
    private lateinit var startActivityForResult: ActivityResultLauncher<Intent>
    private lateinit var s: GetListTypeModel

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setTitleWhiteAndTextBlank()
        setContentView(R.layout.activity_select_machine_list)
        initTitleWithLine(getString(R.string.choose_machine))

        srl = findViewById(R.id.activity_select_machine_list_srl)
        recycler = findViewById(R.id.activity_select_machine_list_recycler)

        startActivityForResult = registerForActivityResult(IntentIntActivityResultContact()) {
            if (it == 1024) {
                finish()
            }
        }

        srl.setOnRefreshListener {
            pageNo = 1
            srl.setEnableLoadMore(true)
            getData()
        }

        srl.setOnLoadMoreListener {
            pageNo++
            getData()
        }

        recycler.layoutManager = LinearLayoutManager(this)
        recycler.addItemDecoration(SpacesItemDecoration(dp2px(16f)))

        adapter = SelectMachineListAdapter(this, list, object : OnMultiClickListener() {
            override fun onMultiClick(v: View?) {
                s = v?.tag as GetListTypeModel

                SBApplication.getBlueToothUtils()

                if (SBApplication.getBlueToothUtils().mBluetoothAdapter == null) {
                    showToast("当前设备不支持蓝牙")
                    return
                }

                val rxPermissions = RxPermissions(this@SelectMachineListActivity)
                rxPermissions.request(*locationPermissions).subscribe {
                    if (it) {
                        // 没有打开蓝牙
                        if (!SBApplication.getBlueToothUtils().mBluetoothAdapter.isEnabled) {
                            val enableBtIntent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
                            startActivityForResult(enableBtIntent, REQUEST_ENBLE_BT)
                        } else {
                            SBApplication.getBlueToothUtils().pairBlueTooth()
                            if (s.deviceType == 1) {
                                var weightNum = 0
                                SBApplication.getBlueToothUtils().scanDevices?.forEach { i ->
                                    if (i.deviceType == 1) {
                                        weightNum++
                                    }
                                }
                                if (weightNum > 1) {
                                    val intent = Intent(this@SelectMachineListActivity, BindWeightThreeActivity::class.java)
                                    startActivityForResult.launch(intent)
                                } else {
                                    val intent = Intent(this@SelectMachineListActivity, BindWeightOneActivity::class.java)
                                    startActivityForResult.launch(intent)
                                }
                            } else if (s.deviceType == 2) {
                                var heightNum = 0
                                SBApplication.getBlueToothUtils().scanDevices?.forEach { i ->
                                    if (i.deviceType == 2) {
                                        heightNum++
                                    }
                                }
                                if (heightNum > 1) {
                                    val intent = Intent(this@SelectMachineListActivity, BindHeightThreeActivity::class.java)
                                    startActivityForResult.launch(intent)
                                } else {
                                    val intent = Intent(this@SelectMachineListActivity, BindHeightOneActivity::class.java)
                                    startActivityForResult.launch(intent)
                                }
                            } else if (s.deviceType == 3) {
                                if (SBApplication.checkHasChildren()) {
                                    if (SBApplication.userData.children!!.size > 1) {
                                        val bottomSingleBabySelectSheet = BottomSingleBabySelectSheet(this@SelectMachineListActivity,/* SBApplication.startCalculate.value!!, */3, SBApplication.userData.children!![0].childId, SBApplication.userData.children!!, object : GetChildIdListener {
                                            override fun getChildId(childId: Int) {
                                                gotoBindToothBrushActivity(childId)
                                            }
                                        })
                                        bottomSingleBabySelectSheet.show()
                                    } else {
                                        gotoBindToothBrushActivity(SBApplication.userData.children!![0].childId)
                                    }
                                } else {
                                    getAddChildDialog(this@SelectMachineListActivity) { ARouter.getInstance().build(BABY_ROUTE).withInt(KeyString.type, 0).navigation() }
                                }
                            }
                        }
                    } else {
                        showToast("蓝牙功能需要获取GPS位置权限才能扫描到设备")
                    }
                }
            }
        })

        recycler.adapter = adapter
        getData()
    }

    private fun getData() {
        val req = PageNumAndPageSizeRequest(pageNo, pageSize)
        HttpHelper().getListType(req)?.subscribe({
            if (pageNo == 1) {
                srl.finishRefresh()
                adapter.setData(it.list)
            } else {
                srl.finishLoadMore()
                adapter.addData(it.list)
            }
            if (pageNo == it.pageTotal) {
                srl.setEnableLoadMore(false)
            }
        }, {
            srl.finishRefresh()
            srl.finishLoadMore()
            showToast(it.message)
        })
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == REQUEST_ENBLE_BT && resultCode == RESULT_OK) {
            SBApplication.getBlueToothUtils().pairBlueTooth()
            if (s.deviceType == 1) {
                var weightNum = 0
                SBApplication.getBlueToothUtils().scanDevices?.forEach {
                    if (it.deviceType == 1) {
                        weightNum++
                    }
                }
                if (weightNum > 1) {
                    val intent = Intent(this@SelectMachineListActivity, BindWeightThreeActivity::class.java)
                    startActivityForResult.launch(intent)
                } else {
                    val intent = Intent(this@SelectMachineListActivity, BindWeightOneActivity::class.java)
                    startActivityForResult.launch(intent)
                }
            } else if (s.deviceType == 2) {
                var heightNum = 0
                SBApplication.getBlueToothUtils().scanDevices?.forEach {
                    if (it.deviceType == 2) {
                        heightNum++
                    }
                }
                if (heightNum > 1) {
                    val intent = Intent(this@SelectMachineListActivity, BindHeightThreeActivity::class.java)
                    startActivityForResult.launch(intent)
                } else {
                    val intent = Intent(this@SelectMachineListActivity, BindHeightOneActivity::class.java)
                    startActivityForResult.launch(intent)
                }
            } else if (s.deviceType == 3) {
                if (SBApplication.checkHasChildren()) {
                    if (SBApplication.userData.children!!.size > 1) {
                        val bottomSingleBabySelectSheet = BottomSingleBabySelectSheet(this, /*SBApplication.startCalculate.value!!,*/ 3, SBApplication.userData.children!![0].childId, SBApplication.userData.children!!, object : GetChildIdListener {
                            override fun getChildId(childId: Int) {
                                gotoBindToothBrushActivity(childId)
                            }
                        })
                        bottomSingleBabySelectSheet.show()
                    } else {
                        gotoBindToothBrushActivity(SBApplication.userData.children!![0].childId)
                    }
                } else {
                    getAddChildDialog(this@SelectMachineListActivity) { ARouter.getInstance().build(BABY_ROUTE).withInt(KeyString.type, 0).navigation() }
                }
            }
        } else if (requestCode == REQUEST_ENBLE_BT && resultCode != RESULT_OK) {
            showToast("请打开手机蓝牙后再试")
        }
    }

    private fun gotoBindToothBrushActivity(childId: Int) {
        var bluetoothNum = 0
        SBApplication.getBlueToothUtils().scanDevices?.forEach {
            if (it.deviceType == 3) {
                bluetoothNum++
            }
        }
        if (bluetoothNum > 1) {
            val intent = Intent(this@SelectMachineListActivity, BindToothBrushThreeActivity::class.java)
            intent.putExtra(KeyString.childId, childId)
            startActivityForResult.launch(intent)
        } else {
            val intent = Intent(this@SelectMachineListActivity, BindToothBrushOneActivity::class.java)
            intent.putExtra(KeyString.childId, childId)
            startActivityForResult.launch(intent)
        }
    }
}